open Printf
open PortMidi
open PortTime

let callback = ref None

let tick (t: timestamp) =
	match !callback with Some f -> f t | None -> ()

let _ =
	Gc.set { (Gc.get ()) with Gc.verbose = 0xFFF };
	initialize ();
	at_exit terminate;
	let default_input = get_default_input_device_id ()
	and default_output = get_default_output_device_id () in
	for i = 0 to count_devices () - 1 do
		let info = get_device_info i in
		printf "[%s] %s (" info.interf info.name;
		if i = default_input then printf "default ";
		if info.input then printf "input";
		if info.input && info.output then printf ", ";
		if i = default_output then printf "default ";
		if info.output then printf "output";
		printf ")\n"
	done;
	flush stdout;

	start 1 tick;
	let input = open_input default_input 128 time ()
	and output = open_output_simple 2 128 256 in
	ignore input;
	callback := Some (fun _ ->
		while poll input do
			List.iter
				(fun event ->
					printf "%d: %02X %02X %02X\n"
						event.timestamp
						(int_of_char event.message.[0])
						(int_of_char event.message.[1])
						(int_of_char event.message.[2]))
				(read input 16);
		done;
		flush stdout);
	while true do
		let timestamp = ((time () + 999) / 1000) * 1000 in
		write_short output timestamp "\x90\x24\x76";
		write output [{ message = "\x90\x24\x00"; timestamp = timestamp + 512 }];
		Unix.sleep 2
	done
